<template>
    <div class="main">
        <!-- excel显示-显示为表格（类似） 
           contenteditable 把我们的其他标签变成可以输入的模式
      -->
        <el-button type="primary" @click="exportExcel">Excel导出</el-button>
        <table border="1" id="result" contenteditable="true">
            <tr>
                <template v-for="(sub,subindex) in files[0]" >
                    <!-- eslint-disable-next-line vue/require-v-for-key -->
                    <th>{{(subindex == 0 ?"":String.fromCharCode(65+subindex-1))}}</th>
                </template>
            </tr>
            <tr v-for="(item,index) in files" :key="index">
                <template v-for="sub in item">
                    <!-- eslint-disable-next-line vue/require-v-for-key -->
                    <td> {{sub}} </td>
                </template>
            </tr>
        </table>
    </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import * as $ from 'jquery'
export default {
    name: 'excelExport',
    data() {
        return {
            // files: []
        }
    },
    props: ['files'],
    mounted() {
        
    },
    methods: {
        //导出函数
        exportExcel() {
            // console.log(this.files)
            let csv = this.tableTocsv($('#result')[0])
            // console.log(csv)
            let sheet = this.csvTosheet(csv)
            //   console.log(sheet)
            let blob = this.sheetToblob(sheet);
            //   console.log(blob)
            this.openDownloadDialog(blob, '导出.xlsx')
        },
        //同学们写的时候基本上是在修改这个地方
        tableTocsv(table) {
            // console.log(table)
            let csv = [];
            $(table).find('tr').each(function() {
                let temp = [];
                $(this).find('td').each(function() {
                    temp.push($(this).html())
                })
                temp.shift()
                csv.push(temp.join(','))
            })
            csv.shift()
            //   console.log(csv)
            return csv.join('\n');
        },
        //将csv格式转成 sheet对象
        csvTosheet(csv) {
            let sheet = {};
            csv = csv.split('\n');
            csv.forEach(function(row, i) {
                row = row.split(',');
                if (i == 0) sheet['!ref'] = 'A1:' + String.fromCharCode(65 + row.length - 1) + (csv.length - 1);
                row.forEach(function(col, j) {
                    sheet[String.fromCharCode(65 + j) + (i + 1)] = { v: col };
                })
            })
            return sheet;
        },
        //将一个sheet对象转成最终的excel文件的blob对象 然后下载
        sheetToblob(sheet, sheetName) {
            sheetName = sheetName || 'sheet1'
            let workbook = {
                SheetNames: [sheetName],
                Sheets: {}
            }
            workbook.Sheets[sheetName] = sheet;
            //生成excel的配置项
            let wopts = {
                bookType: 'xlsx',
                bookSST: false,
                type: 'binary'
            }
            let wbout = XLSX.write(workbook, wopts);
            let blob = new Blob([sab(wbout)], { type: 'application/octet-stream' });
            //把字符串转化成 arrayBuffer(类型化数组)
            function sab(s) {
                let buf = new ArrayBuffer(s.length);
                let view = new Uint8Array(buf);
                for (let i = 0; i != s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
                return buf
            }
            return blob
        },
        //通用的打开下载对话框方法
        openDownloadDialog(url, saveName) {
            if (typeof url == 'object' && url instanceof Blob) {
                url = URL.createObjectURL(url); //创建blob地址
            }
            let aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = saveName || '';
            let event;
            if (window.MouseEvent) event = new MouseEvent('click');
            else {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            //触发事件
            aLink.dispatchEvent(event)
        }
    },
}
</script>
<style scoped>

</style>
